package com.nowcoder.community.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author cjh
 * @date 2023/1/11 - 11:51
 */
@Component
@Aspect
@Slf4j
public class ServiceLogAspect {
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinpoint) {
//        用户【1.2.3.4】在【xxx】 访问了【com.nowcoder.community.service.xxx()】
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        当不是从controller中调用 时
        if (attributes == null) {
            return;
        }

        HttpServletRequest request = attributes.getRequest();


        String ip = request.getRemoteHost();
        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String now = df.format(LocalDateTime.now());
        String target = joinpoint.getSignature().getDeclaringTypeName() + "." + joinpoint.getSignature().getName();

        log.info(String.format("用户[%s],在[%s],访问了[%s]", ip, now, target));
    }
}
